using System;
using RomanJendrusz.Amazon.ETL.Domain;
using System.Collections.Generic;
using RomanJendrusz.Amazon.ETL.Repositories;
using RomanJendrusz.Amazon.ETL.Services;
using RomanJendrusz.Amazon.ETL.Infrastructure.Loging.Core;
namespace RomanJendrusz.Amazon.ETL.Tasks
{
    public class SellerOfferTask
    {
        private readonly IMarketPlaceService marketPlaceService;
        private readonly IUnitOfWork unitOfWork;
        private List<Book> booksChecked;

        public SellerOfferTask(IMarketPlaceService marketPlaceService,  IUnitOfWork unitOfWork)
        {
            this.marketPlaceService = marketPlaceService;
            this.unitOfWork = unitOfWork;
            booksChecked = new List<Book>();
        }

        public IList<SellerOffer> RetrieveSellerOffersFor(Book book)
        {
            if (book == null) throw new ArgumentNullException("book");
            if (booksChecked.Contains(book))
            {
                LogGateway.LogFor(GetType()).Warn(string.Format("Seller Offers for book {0} with asin {1} were allready retrieved", book.Title, book.Asin));
                return null;
            }
            if (book.Updated > AmazonConstants.OlderEntityDate)
            {
                LogGateway.LogFor(GetType()).Warn(string.Format("Seller Offers for book {0} with asin {1} were retrieved earlier then the update entity date", book.Title, book.Asin));
                return null;
            }
            var offersRepository = unitOfWork.SellerOffersRepository;
            LogGateway.LogFor(GetType()).Warn(string.Format("Retrieving seller offers informations for book {0} with asin {1}", book.Title, book.Asin));
            var offers = marketPlaceService.GetActualSellerOffersFor(book);
            foreach (var offer in offers)
            {
                offersRepository.Add(offersRepository.AttachIfAllreadyExists(offer));
            }
            unitOfWork.SubmitChanges();
            booksChecked.Add(book);
            return offers;
        }
    }
}